<%@ include file="inc.jsp"%>
<%
	//get parameters
	String username = request.getParameter("username");
	String password1 = request.getParameter("password1");
	String password2 = request.getParameter("password2");
	String email = request.getParameter("email");
	
	//check null
	//若参数未填，则为""，而非null
	if (username.equals("") || password1.equals("") || password2.equals("") || !password1.equals(password2))
		response.sendRedirect("register.jsp");
	else { //response.sendRedirect("register.jsp")会在所有代码执行完毕后再执行，因此此处else必须存在，否则下面的代码依然会执行
		//validate
		//未考虑多线程并发的情况
		boolean isValid = false;
		String sql = "select * from user where username = '" + username + "'";
		try {
			Class.forName(drv).newInstance();
			Connection conn = DriverManager.getConnection(url, usr, pwd);
			Statement stm = conn.createStatement();
			ResultSet rs = stm.executeQuery(sql);
			if (!rs.next()) {
				sql = "insert into user(username, password, email) values('" + username + "', '" + password1 + "', '" + email + "')";
				stm.execute(sql);
				isValid = true;
			}
			
			rs.close();
			stm.close();
			conn.close();
		} catch(Exception e) {
			e.printStackTrace();
			out.println(e);
		}
		
		if (isValid)
			response.sendRedirect("login.jsp");
		else
			response.sendRedirect("register.jsp");
	}
%>	